package com.share.four.netty.marshalling;

import java.io.FileOutputStream;

import com.share.four.netty.marshalling.entity.Req;
import com.share.four.netty.marshalling.entity.Resp;
import com.share.four.netty.marshalling.util.GzipUtils;
import com.share.gzip.gzipTest;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import io.netty.util.ReferenceCountUtil;

/*
 * ChannelHandlerAdapter.class--->适配器设计模式：目的是不用重写接口中的每个方法，只重写需要的
 */
public class ServerHandler extends ChannelHandlerAdapter{

	/* 
	 * description： 在不接受任何请求时, 只是在连接被创建时，会执行此方法
	 */
	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		System.out.println("server channel active");
	}

	/* 
	 * @description: 每当从客户端收到新的数据时，这个方法会在收到消息时被调用
	 * msg: client端发送过来的数据
	 * ctx: server端与client端的channel
	 */
	@SuppressWarnings("resource")
	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

		try {
			Req req = (Req)msg;
			System.out.println("server 接收： " + "id=" + req.getId() + "name=" + req.getName() + "RequestMessage" + req.getRequestMessage());
			
			byte[] arr = req.getAttachment();
			byte[] unGzip = GzipUtils.unGzip(arr);
			
			FileOutputStream fout = new FileOutputStream("marshalling.jpg");
			fout.write(unGzip);
			fout.close();
			
			final Resp resp = new Resp();
			resp.setId(req.getId());
			resp.setName(req.getName());
			resp.setResponseMessage("responseMessage");
			
			
			ctx.writeAndFlush(resp).addListener(new ChannelFutureListener() {
				
				@Override
				public void operationComplete(ChannelFuture future) throws Exception {
					System.out.println("server 发送" + resp);
					
				}
			});
		} finally {
			//DISCARD服务(丢弃服务，指的是会忽略所有接收的数据的一种协议)
			ReferenceCountUtil.release(msg);
		}

	}

	/* 
	 * @description: 当Netty由于IO错误或者处理器在处理事件时抛出的异常时,该方法被调用
	 */
	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		cause.printStackTrace();
		ctx.close();
	}


}
